//
// Created by korack on 25-5-17.
//

#include "Network.h"
#include <giomm/networkaddress.h>
#include <giomm/socket.h>

namespace Mp {

Network::Network()
  : m_socketClient(Gio::SocketClient::create()), is_connected(false)
{
  m_socketClient->set_timeout(3);
  m_socketClient->set_family(Gio::SocketFamily::IPV4);
  m_socketClient->set_socket_type(Gio::Socket::Type::STREAM);
}

Network::~Network() { close_connection(); }

Glib::RefPtr<Network>
Network::create()
{
  return Glib::make_refptr_for_instance<Network>(new Network);
}

void
Network::send_messages(const std::string &msg_type,
		       const std::string &message) const
{
  const std::string command = "zncdz,devType=ADMIN,msgType=" + msg_type
			      + ",devID=administrator-01," + message;
  out_stream->write(command);
}

void
Network::connect_to_server(const std::string &server_address, const int port)
{
  const Glib::RefPtr<Gio::NetworkAddress> address
    = Gio::NetworkAddress::create(server_address, port);
  conn = m_socketClient->connect(address);
  out_stream = conn->get_output_stream();
  in_stream = conn->get_input_stream();
}

void
Network::register_to_server() const
{
  const std::string command
    = "zncdz,devType=ADMIN,msgType=REG,devID=administrator-01";
  out_stream->write(command);
}

void
Network::close_connection() const
{
  out_stream->close();
  in_stream->close();
  conn->close();
}

} // namespace Mp